package com.timemanage.activity.ui.mine

import android.Manifest
import android.R.attr
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.*

import android.webkit.WebView

import androidx.appcompat.app.AppCompatDelegate
import androidx.core.app.NotificationCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.timemanage.R

import com.timemanage.dao.Image
import com.timemanage.dao.ImageResponse
import com.timemanage.network.HttpUtil

import com.timemanage.network.Wisdom

import com.timemanage.activity.loginActiviy
import com.timemanage.dao.AppDatabase
import com.timemanage.dao.UserDao

import com.timemanage.utils.AlarmService
import com.timemanage.utils.MyApplication
import kotlinx.android.synthetic.main.mine_fragment.*

import kotlinx.android.synthetic.main.nav_head.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response

import java.util.*

import androidx.core.app.ActivityCompat.startActivityForResult

import android.provider.MediaStore

import androidx.core.content.FileProvider

import androidx.core.app.ActivityCompat

import android.content.pm.PackageManager
import android.graphics.Color

import androidx.core.content.ContextCompat

import android.view.Gravity

import android.view.WindowManager

import android.graphics.drawable.ColorDrawable
import android.graphics.BitmapFactory

import android.graphics.Bitmap

import android.provider.DocumentsContract

import android.annotation.TargetApi
import android.app.Activity.RESULT_OK
import android.database.Cursor
import android.os.Build
import android.widget.*

import androidx.core.app.ActivityCompat.startActivityForResult
import com.google.android.material.navigation.NavigationView
import de.hdodenhof.circleimageview.CircleImageView
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import android.content.SharedPreferences.Editor
import android.util.Base64

import java.io.ByteArrayOutputStream
import android.R.attr.data
import android.content.*
import java.io.ByteArrayInputStream




class MineFragment : Fragment() {


    companion object {
        var click = 1
        fun newInstance() = MineFragment()
    }
    lateinit var quitBtn : TextView
    private var pop: PopupWindow? = null
    val TAKE_PHOTO = 1
    private var imageUri: Uri? = null
    val CHOOSE_PHOTO = 2

    lateinit var picture : CircleImageView
    lateinit var view1: View
    lateinit var navi: NavigationView
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val view= inflater.inflate(R.layout.mine_fragment, container, false)
//        view1 = inflater.inflate(R.layout.nav_head, container, false)
        navi = view.findViewById(R.id.navView)

        picture = navi.getHeaderView(0).findViewById(R.id.iconImage)


        quitBtn = view.findViewById(R.id.quit)

        return view
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        getBitmapFromSharedPreferences()

        picture.setOnClickListener {
            Log.d("aaa","asdsadsadsad")
            showPop()
        }

//        var builder = NotificationCompat.Builder(MyApplication.context,"提醒" )
//            .setContentTitle("你好")
//            .setContentText("sb")
//            .setPriority(NotificationCompat.PRIORITY_DEFAULT)

        quitBtn.setOnClickListener{
            Log.d("dianji","点击")
            var database= AppDatabase.getDatabase(MyApplication.context)
            var userdao: UserDao =database.userDao();
            var users = userdao.selectAcUser()
            userdao.quit(users.userId)
            val intent = Intent(context, loginActiviy::class.java)
            startActivity(intent)
        }



        caution.setOnClickListener {
            val intent = Intent(this.context, AlarmService::class.java)
            intent.setPackage(MyApplication.context.packageName)
            activity?.startService(intent) // 启动Service
            AlertDialog.Builder(this.context).setMessage("设置成功!").show()
        }

        law.setOnClickListener {

        }

//        exit.setOnClickListener {
//
//        }

        synchronism.setOnClickListener {


        }
        updata.setOnClickListener {

        }

        about.setOnClickListener {

            val intent = Intent(Intent.ACTION_VIEW)
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(Uri.parse("http://47.94.11.35:8080"))
            startActivity(intent)
        }
        night.setOnClickListener {
            if (MineFragment.click % 2 == 0)
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            else
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            MineFragment.click++
        }

    }


    private fun showPop() {
        val bottomView = View.inflate(activity, R.layout.bottom_dialog, null)
        val mAlbum: TextView = bottomView.findViewById(R.id.tv_album)
        val mCamera: TextView = bottomView.findViewById(R.id.tv_camera)
        val mCancel: TextView = bottomView.findViewById(R.id.tv_cancel)
        pop = PopupWindow(bottomView, -1, -2)
        pop!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        pop!!.setOutsideTouchable(true)
        pop!!.setFocusable(true)
        val lp = requireActivity().window.attributes
        lp.alpha = 0.5f
        requireActivity().window.attributes = lp
        pop!!.setOnDismissListener(PopupWindow.OnDismissListener {
            val lp = requireActivity().window.attributes
            lp.alpha = 1f
            requireActivity().window.attributes = lp
        })
        pop!!.setAnimationStyle(R.style.main_menu_photo_anim)
        pop!!.showAtLocation(requireActivity().window.decorView, Gravity.BOTTOM, 0, 0)
        val clickListener: View.OnClickListener = View.OnClickListener() {
          //  override fun onClick(view: View) {
                when (it.id) {
                    R.id.tv_album ->                         //相册
                        if (ContextCompat.checkSelfPermission(
                                requireActivity(),
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ) != PackageManager.PERMISSION_GRANTED
                        ) {
                            //相册中的照片都是存储在SD卡上的，需要申请运行时权限，WRITE_EXTERNAL_STORAGE是危险权限，表示同时授予程序对SD卡的读和写的能力
                            ActivityCompat.requestPermissions(
                                requireActivity(),
                                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                1
                            )
                        } else {
                            openAlbum()
                        }
                    R.id.tv_camera -> {
                        //拍照
                        val outputImage = File(requireActivity().externalCacheDir, "output_image.jpg")
                        try {
                            if (outputImage.exists()) outputImage.delete()
                            outputImage.createNewFile()
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                        if (Build.VERSION.SDK_INT >= 24) {
                            imageUri = FileProvider.getUriForFile(
                                requireActivity(),
                                "com.example.cameraalbumtest.fileprovider", outputImage
                            )
                        } else {
                            imageUri = Uri.fromFile(outputImage)
                        }
                        val intent = Intent("android.media.action.IMAGE_CAPTURE")
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
                        startActivityForResult(intent, TAKE_PHOTO)
                    }
                    R.id.tv_cancel ->                         //取消
                        closePopupWindow()
                }
                closePopupWindow()
            }
        //}
        mCamera.setOnClickListener(clickListener)
        mAlbum.setOnClickListener(clickListener)
        mCancel.setOnClickListener(clickListener)
    }

    fun closePopupWindow() {
        if (pop != null && pop!!.isShowing) {
            pop!!.dismiss()
            pop = null
        }
    }

    private fun openAlbum() {
        val intent = Intent("android.intent.action.GET_CONTENT")
        intent.type = "image/*"
        startActivityForResult(intent, CHOOSE_PHOTO) //打开相册
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            TAKE_PHOTO -> if (resultCode == RESULT_OK) {
                try {
                    val bitmap = BitmapFactory.decodeStream(
                        imageUri?.let { requireActivity().contentResolver.openInputStream(it) }
                    )
//                    val bitmap: Bitmap = attr.data.getParcelableExtra("data")
//                    picture.setImageBitmap(bitmap)
                } catch (e: FileNotFoundException) {
                    e.printStackTrace()
                }
            }
            CHOOSE_PHOTO -> if (resultCode == RESULT_OK) {
                //因为sdk19以后返回的数据不同，所以要根据手机系统版本进行不同的操作
                //判断手机系统版本
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKiKai(data!!)
                } else {
                    handleImageBeforeKiKai(data!!)
                }
            }
            else -> {
            }
        }
    }

    //>=19的操作
    @TargetApi(19)
    private fun handleImageOnKiKai(data: Intent) {
        var imagePath: String? = null
        val uri = data.data
        if (DocumentsContract.isDocumentUri(activity, uri)) {
            //如果是Document类型的Uri，则通过document id 处理
            val docId = DocumentsContract.getDocumentId(uri)
            if ("com.android.providers.media.documents" == uri!!.authority) {
                val id = docId.split(":").toTypedArray()[1]
                val selection = MediaStore.Images.Media._ID + "=" + id
                imagePath = getImagePath(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection
                )
            } else if ("com.android.providers.downloads.documents" == uri.authority) {
                val contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(docId)
                )
                imagePath = getImagePath(contentUri, null)
            } else if ("content".equals(uri.scheme, ignoreCase = true)) {
                //不是document类型的Uri，普通方法处理
                imagePath = getImagePath(uri, null)
            }
            displayImage(imagePath)
        }
    }

    //<19的操作
    private fun handleImageBeforeKiKai(data: Intent) {
        val uri = data.data
        val imagePath = getImagePath(uri, null)
        displayImage(imagePath)
    }

    @SuppressLint("Range")
    private fun getImagePath(uri: Uri?, selection: String?): String? {
        var path: String? = null
        //通过Uri 和selection获取真正的图片路径
        val cursor: Cursor? = requireActivity().contentResolver.query(
            uri!!, null, selection, null, null
        )
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(
                    cursor.getColumnIndex(MediaStore.Images.Media.DATA)
                )
            }
            cursor.close()
        }
        return path
    }

    private fun displayImage(path: String?) {
        if (path != null) {
            val bitmap = BitmapFactory.decodeFile(path)
            //路径存到文件中，OnCreate里调用该函数
            saveBitmapToSharedPreferences(bitmap)
            picture.setImageBitmap(bitmap)
        } else {
            Toast.makeText(activity, "Load Failed", Toast.LENGTH_LONG).show()
        }
    }



        fun getImage() {
            val images = MutableLiveData<List<Image>>()
            val currentImage = MutableLiveData<Image>()
            val url: String = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=10"
            HttpUtil.senOkHttpRequest(url, object: Callback {
                override fun onResponse(call: Call, response: Response) {
                    val responseData = response.body()?.string()
                    if (responseData != null) {
                        Log.d("MyTag", responseData)
                        val _images = parseJSONWithGSON(responseData)
                        for (image in _images) {
                            image.url = "https://cn.bing.com/" + image.url
                        }
                        images.postValue(_images)
                        currentImage.postValue(_images[0])
                    }
                }

                override fun onFailure(call: Call, e: IOException) {
                    Log.d("MyTag", e.toString())
                }
            })
        }


        fun parseJSONWithGSON(responseData: String): List<Image> {
            val gson = Gson()
            val results = gson.fromJson(responseData, ImageResponse::class.java)
            return results.images
        }





    private fun saveBitmapToSharedPreferences(bitmap: Bitmap) {
        // Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        //第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
        val byteArrayOutputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream)
        //第二步:利用Base64将字节数组输出流中的数据转换成字符串String
        val byteArray = byteArrayOutputStream.toByteArray()
        val imageString = (Base64.encodeToString(byteArray, Base64.DEFAULT)) as String
        //第三步:将String保持至SharedPreferences
        val sharedPreferences = this.activity?.getSharedPreferences("testSP", Context.MODE_PRIVATE)
        val editor = sharedPreferences?.edit()
        editor?.putString("image", imageString)
        editor?.commit()

    }

    //从SharedPreferences获取图片
    private fun getBitmapFromSharedPreferences() {
        val sharedPreferences=
            this.activity?.getSharedPreferences("testSP", Context.MODE_PRIVATE)
        //第一步:取出字符串形式的Bitmap
        val imageString = sharedPreferences?.getString("image", "")
        //第二步:利用Base64将字符串转换为ByteArrayInputStream
        val byteArray = Base64.decode(imageString, Base64.DEFAULT)
        if (byteArray.size == 0) {
            picture.setImageResource(R.drawable.headimg)
        } else {
            val byteArrayInputStream = ByteArrayInputStream(byteArray)
            //第三步:利用ByteArrayInputStream生成Bitmap
            val bitmap = BitmapFactory.decodeStream(byteArrayInputStream)
            picture.setImageBitmap(bitmap)
        }
    }

}

